'use client'

import { useState, useMemo } from 'react'
import { Button } from '@/components/ui/button'
import { copyToClipboard } from '@/lib/utils'
import { Copy, RotateCcw, FileText, Hash, Clock } from 'lucide-react'

interface TextStats {
  characters: number
  charactersNoSpaces: number
  words: number
  sentences: number
  paragraphs: number
  lines: number
  readingTime: number // 分钟
  speakingTime: number // 分钟
}

export default function WordCounterPage() {
  const [input, setInput] = useState('')
  const [copySuccess, setCopySuccess] = useState(false)

  const stats: TextStats = useMemo(() => {
    if (!input) {
      return {
        characters: 0,
        charactersNoSpaces: 0,
        words: 0,
        sentences: 0,
        paragraphs: 0,
        lines: 0,
        readingTime: 0,
        speakingTime: 0
      }
    }

    const characters = input.length
    const charactersNoSpaces = input.replace(/\s/g, '').length
    
    // 计算单词数（支持中英文）
    const words = input
      .trim()
      .split(/\s+/)
      .filter(word => word.length > 0).length
    
    // 计算句子数
    const sentences = input
      .split(/[.!?。！？]+/)
      .filter(sentence => sentence.trim().length > 0).length
    
    // 计算段落数
    const paragraphs = input
      .split(/\n\s*\n/)
      .filter(paragraph => paragraph.trim().length > 0).length
    
    // 计算行数
    const lines = input.split('\n').length
    
    // 计算阅读时间（假设每分钟200个单词）
    const readingTime = Math.ceil(words / 200)
    
    // 计算朗读时间（假设每分钟150个单词）
    const speakingTime = Math.ceil(words / 150)

    return {
      characters,
      charactersNoSpaces,
      words,
      sentences,
      paragraphs,
      lines,
      readingTime,
      speakingTime
    }
  }, [input])

  const handleClear = () => {
    setInput('')
  }

  const handleCopyStats = async () => {
    const statsText = `文本统计结果：
字符数：${stats.characters}
字符数（不含空格）：${stats.charactersNoSpaces}
单词数：${stats.words}
句子数：${stats.sentences}
段落数：${stats.paragraphs}
行数：${stats.lines}
预计阅读时间：${stats.readingTime}分钟
预计朗读时间：${stats.speakingTime}分钟`
    
    const success = await copyToClipboard(statsText)
    if (success) {
      setCopySuccess(true)
      setTimeout(() => setCopySuccess(false), 2000)
    }
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target?.result as string
        setInput(content)
      }
      reader.readAsText(file)
    }
  }

  const statItems = [
    {
      label: '字符数',
      value: stats.characters.toLocaleString(),
      icon: Hash,
      color: 'blue'
    },
    {
      label: '字符数（不含空格）',
      value: stats.charactersNoSpaces.toLocaleString(),
      icon: Hash,
      color: 'green'
    },
    {
      label: '单词数',
      value: stats.words.toLocaleString(),
      icon: FileText,
      color: 'purple'
    },
    {
      label: '句子数',
      value: stats.sentences.toLocaleString(),
      icon: FileText,
      color: 'orange'
    },
    {
      label: '段落数',
      value: stats.paragraphs.toLocaleString(),
      icon: FileText,
      color: 'red'
    },
    {
      label: '行数',
      value: stats.lines.toLocaleString(),
      icon: FileText,
      color: 'indigo'
    },
    {
      label: '预计阅读时间',
      value: `${stats.readingTime}分钟`,
      icon: Clock,
      color: 'teal'
    },
    {
      label: '预计朗读时间',
      value: `${stats.speakingTime}分钟`,
      icon: Clock,
      color: 'pink'
    }
  ]

  const getColorClasses = (color: string) => {
    const colorMap: Record<string, string> = {
      blue: 'bg-blue-50 text-blue-700 border-blue-200',
      green: 'bg-green-50 text-green-700 border-green-200',
      purple: 'bg-purple-50 text-purple-700 border-purple-200',
      orange: 'bg-orange-50 text-orange-700 border-orange-200',
      red: 'bg-red-50 text-red-700 border-red-200',
      indigo: 'bg-indigo-50 text-indigo-700 border-indigo-200',
      teal: 'bg-teal-50 text-teal-700 border-teal-200',
      pink: 'bg-pink-50 text-pink-700 border-pink-200'
    }
    return colorMap[color] || 'bg-gray-50 text-gray-700 border-gray-200'
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            字数统计工具
          </h1>
          <p className="text-gray-600">
            实时统计文本的字符数、单词数、句子数等详细信息
          </p>
        </div>

        {/* Controls */}
        <div className="flex flex-wrap items-center gap-4 mb-6">
          <Button variant="outline" onClick={handleClear}>
            <RotateCcw className="w-4 h-4 mr-2" />
            清空
          </Button>
          
          <div className="relative">
            <input
              type="file"
              accept=".txt,.md,.doc,.docx"
              onChange={handleFileUpload}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            />
            <Button variant="outline">
              <FileText className="w-4 h-4 mr-2" />
              上传文件
            </Button>
          </div>
          
          <Button onClick={handleCopyStats} disabled={!input}>
            <Copy className="w-4 h-4 mr-2" />
            {copySuccess ? '已复制统计' : '复制统计'}
          </Button>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Input */}
          <div className="lg:col-span-2 space-y-2">
            <label className="text-sm font-medium text-gray-700">
              输入文本
            </label>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="请输入或粘贴要统计的文本内容..."
              className="w-full h-96 p-4 border border-gray-300 rounded-lg text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Stats */}
          <div className="space-y-4">
            <h2 className="text-lg font-semibold text-gray-900">
              统计结果
            </h2>
            
            <div className="grid gap-3">
              {statItems.map((item) => {
                const Icon = item.icon
                return (
                  <div
                    key={item.label}
                    className={`p-4 rounded-lg border ${getColorClasses(item.color)}`}
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <Icon className="w-4 h-4" />
                      <span className="text-sm font-medium">
                        {item.label}
                      </span>
                    </div>
                    <div className="text-2xl font-bold">
                      {item.value}
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        </div>

        {/* Features */}
        <div className="mt-12 grid grid-cols-1 md:grid-cols-4 gap-6">
          <div className="text-center p-6 bg-blue-50 rounded-lg">
            <h3 className="font-semibold text-blue-900 mb-2">实时统计</h3>
            <p className="text-blue-700 text-sm">
              输入文本时实时更新统计数据
            </p>
          </div>
          <div className="text-center p-6 bg-green-50 rounded-lg">
            <h3 className="font-semibold text-green-900 mb-2">多维度分析</h3>
            <p className="text-green-700 text-sm">
              提供字符、单词、句子等多种统计
            </p>
          </div>
          <div className="text-center p-6 bg-purple-50 rounded-lg">
            <h3 className="font-semibold text-purple-900 mb-2">时间预估</h3>
            <p className="text-purple-700 text-sm">
              预估阅读和朗读所需时间
            </p>
          </div>
          <div className="text-center p-6 bg-orange-50 rounded-lg">
            <h3 className="font-semibold text-orange-900 mb-2">文件支持</h3>
            <p className="text-orange-700 text-sm">
              支持上传文本文件进行统计
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}